//
//  MBShortVideoImportLocalVideoHelp.m
//  LiveBroadcast
//
//  Created by Maybe on 2019/5/2.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "MBShortVideoImportLocalVideoHelp.h"
#import "MBShortVideoEditController.h"


@interface MBShortVideoImportLocalVideoHelp ()<TXVideoGenerateListener>

@property (strong, nonatomic) NSMutableArray *localPaths;
@property (strong, nonatomic)NSArray        *assets;
@property (strong, nonatomic)NSMutableArray     *videosToEditAssets;
@property (strong, nonatomic) NSMutableArray     *imagesToEdit;
@property (assign, nonatomic) NSUInteger  exportIndex;
@property (strong, nonatomic)AVMutableComposition *mutableComposition;
@property (strong, nonatomic)AVMutableVideoComposition *mutableVideoComposition;
@property (nonatomic, strong)UIViewController *fromVC;
@property (nonatomic, strong)UIImage *coverImage;
@property (nonatomic, assign)MBShortVideoEntityType fromType;

@end



@implementation MBShortVideoImportLocalVideoHelp{
    BOOL  _loadingIsInterrupt;
    TXVideoEditer *_editor;
    NSString *_tempPath;
}

#pragma mark - 导入本地视频


- (void)exportAssetList:(NSArray *)assets fromController:(UIViewController *)fromVC coverImage:(nonnull UIImage *)coverImage entity:(MBShortVideoEntityType)type{
    _assets = assets;
    _exportIndex = 0;
    _localPaths = [NSMutableArray new];
    _videosToEditAssets = [NSMutableArray array];
    _fromVC = fromVC;
    _coverImage = coverImage;
    _fromType = type;
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD showActivityMessage:@"视频正在解码中，请稍等..."];
    });
    [self exportAssetInternal];
}

- (void)exportAssetInternal {
    if (_exportIndex == _assets.count) {
        AVAsset *asset = _videosToEditAssets.firstObject;
        TXVideoInfo *info = [TXVideoInfoReader getVideoInfoWithAsset:asset];
        if (info.width * info.height > 1920*1080) {
            [self beginCompressTo720AndNavigateToEdit:asset];
            return;
        }
        MBShortVideoEditController *vc = [[MBShortVideoEditController alloc]init];
        vc.videoAsset = _videosToEditAssets[0];
        vc.coverImage = self.coverImage;
        if(!_loadingIsInterrupt) {
            [MBProgressHUD hideHUD];
            vc.entityType = _fromType;
            [_fromVC.navigationController pushViewController:vc animated:YES];
            return;
        }
    }
    self.mutableComposition = nil;
    self.mutableVideoComposition = nil;
    __weak __typeof(self) weakSelf = self;
    PHAsset *expAsset = _assets[_exportIndex];
    PHVideoRequestOptions *options = [PHVideoRequestOptions new];
    // 最高质量的视频
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeHighQualityFormat;
    // 可从iCloud中获取图片
    options.networkAccessAllowed = NO;
    // 如果是iCloud的视频，可以获取到下载进度
    options.progressHandler = ^(double progress, NSError * _Nullable error, BOOL * _Nonnull stop, NSDictionary * _Nullable info) {
        *stop = _loadingIsInterrupt;
    };
    [[PHImageManager defaultManager] requestAVAssetForVideo:expAsset options:options resultHandler:^(AVAsset * _Nullable avAsset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        //SDK内部通过avAsset 读取视频数据，会极大的降低视频loading时间
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            if (avAsset) {
                [_videosToEditAssets addObject:avAsset];
                _exportIndex++;
                [self exportAssetInternal];
            }
        });
    }];
}

- (void)beginCompressTo720AndNavigateToEdit:(AVAsset *)video {
    TXPreviewParam *param = [[TXPreviewParam alloc] init];
    param.renderMode =  PREVIEW_RENDER_MODE_FILL_EDGE;
    TXVideoEditer *editer = [[TXVideoEditer alloc] initWithPreview:param];
    _editor = editer;
    editer.generateDelegate = self;
    //    editer.previewDelegate = _videoPreview;
    [editer setVideoAsset:video];
    [editer setVideoBitrate:9000];
    NSString *tempFilename = [NSString stringWithFormat:@"%@_720p.mp4", [NSUUID UUID].UUIDString];
    NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:tempFilename];
    _tempPath = tempPath;
    [editer generateVideo:VIDEO_COMPRESSED_720P videoOutputPath:tempPath];
//    [self setProgressTitle:@"视频正在解码中，请稍等..."];
}

#pragma mark TXVideoGenerateListener
-(void) onGenerateComplete:(TXGenerateResult *)result{
    [MBProgressHUD hideHUD];
    if(!_loadingIsInterrupt)  {
        if (result.retCode == GENERATE_RESULT_OK) {
            MBShortVideoEditController *vc = [[MBShortVideoEditController alloc]init];
            //vc.videoPath = _localPaths[0];
            vc.videoPath = _tempPath;
            vc.removeVideoAfterFinish = YES;
            vc.coverImage = _coverImage;
            vc.entityType = _fromType;
            [_fromVC.navigationController pushViewController:vc animated:YES];
            _editor = nil;
        } else {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"导入失败" message:result.descMsg preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
            [alert addAction:confirmAction];
            [_fromVC presentViewController:alert animated:YES completion:nil];
        }
    }
}

@end
